// pages/list/list.js
import {baseApi} from '../../../utils/util.js';
Page({
  data: {
    openid:'',
    items: [],      // 列表数据
    pageNum: 1,        // 当前页码
    pageSize: 10,   // 每页数量
    hasMore: true,  // 是否还有更多数据
    loading: false  // 是否正在加载
  },

  onLoad() {
    var that = this;
    wx.getStorage({
      key: 'openid',
      success (res) {
        console.log(JSON.stringify(res));
        that.data.openid = res.data;
        console.log(res.data);
        that.loadData();
      }
    })
  },

  // 加载数据
  async loadData() {
    if (!this.data.hasMore || this.data.loading) return
    
    this.setData({ loading: true })
    var that = this;
    try {
      var params = {
        pageNum: that.data.pageNum,
        pageSize: that.data.pageSize,
        openid: that.data.openid
      };
      //console.log(JSON.stringify(params));
      wx.request({
        url:  baseApi() + '/app/myApprovalList',
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 关键请求头
        },
        data: params,
        success(res){
          console.log(JSON.stringify(res));
          that.setData({
            items: that.data.items.concat(res.data.rows),
            pageNum: that.data.pageNum + 1,
            hasMore: that.data.pageNum < 5 && res.data.rows.length == that.data.pageSize,
            loading: false
          });
        }
      })
      
    } catch (error) {
      console.error('加载失败:', error)
      this.setData({ loading: false })
    }
  },

  async reloadData() {
    //if (!this.data.hasMore || this.data.loading) return
    
    this.setData({ loading: true })
    var that = this;
    try {
      var params = {
        pageNum: 1,
        pageSize: 5,
        openid: that.data.openid
      };
      console.log(JSON.stringify(params));
      wx.request({
        url:  baseApi() + '/app/myApprovalList',
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 关键请求头
        },
        data: params,
        success(res){
          that.setData({
            items: that.data.items = res.data.rows,
            pageNum: params.pageNum + 1,
            hasMore: res.data.rows.length == that.data.pageSize,
            loading: false
          });
        }
      })
      
    } catch (error) {
      console.error('加载失败:', error)
      this.setData({ loading: false })
    }
  },

  // 点击列表项
  handleItemTap(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/detail/detail?id=${id}'
    })
  },

  // 滑动结束处理
  handleSwipeEnd(e) {
    const x = e.detail.x
    const index = e.currentTarget.dataset.index
    const query = wx.createSelectorQuery().in(this)
    
    // 计算滑动阈值
    query.select('.swipe-item').boundingClientRect(rect => {
      const threshold = -rect.width * 0.3
      if (x < threshold) {
        this.setData({
          [`items[${index}].showDelete`]: true
        })
      } else {
        this.setData({
          [`items[${index}].showDelete`]: false
        })
      }
    }).exec()
  },

  // 删除项目
  deleteItem(e) {
    const id = e.currentTarget.dataset.id
    this.setData({
      items: this.data.items.filter(item => item.id !== id)
    })
    wx.showToast({ title: '删除成功' })
  },
  // 通过
  accept(e){
    var id = e.currentTarget.dataset.id;
    var approvalStatus = e.currentTarget.dataset.status;
    if(approvalStatus == 'A'){
      wx.showToast({
        title: '已审批通过,无法重复审批',
      });
      return;
    }
    this.approval(id,'A');
  },
  // 驳回
  reject(e){
    var id = e.currentTarget.dataset.id;
    var approvalStatus = e.currentTarget.dataset.status;
    if(approvalStatus == 'R'){
      wx.showToast({
        title: '已审批拒绝,无法重复审批',
      });
      return;
    }
    this.approval(id,'R');
  },
  // 审核
  approval(appointmentId,approvalState){
    var that = this;
    var param = {
      appointmentId:appointmentId,
      approvalState:approvalState
    };
    console.log(JSON.stringify(param));
    wx.request({
      url:  baseApi() + '/app/approval',
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      data: param,
      success(res){
        wx.showToast({
          title: '审核完成',
          icon: 'success',
          duration: 2000
        });
        that.reloadData();
      }
    })
  },
  // 加载更多
  loadMore() {
    this.loadData()
  },
  detailItem(e){
    var id = e.currentTarget.dataset.id;
    var approvalStatus = e.currentTarget.dataset.status;
    console.log(approvalStatus);
    wx.navigateTo({
      url: '/pages/visitor/detail/index?id='+id,
    })
  }
})